#!/usr/bin/env ruby
# Copyright (C) 2014 Cisco, Inc.

require 'json'
require 'panoptimon/util'
require 'panoptimon/util/string-with-as_number'

config = ARGV[0] ? JSON::parse(ARGV[0]) : {}
fail "no sysctls supplied" unless config['sysctls'].length >0

sysctls = config['sysctls'].join(' ');

$stdout.sync = true

get_sysctl = Panoptimon::Util.os(
  linux: ->() {
    ->() {
      info = {};
      stats = %x[sysctl #{sysctls}].split("\n").map { |line|
        line.gsub(/\./,"|").split("=").map { |field| field.strip }
      }.map { |each|
        if (each[1].as_number)
          [each[0], each[1].as_number]
        else
          info[each[0]] = each[1]
          []
        end
      }
      $?.success? or fail "sysctl unhappy #{$?.exitstatus}"

      return Hash[ stats + [[:_info, info]] ]
    }
  },
)

while(true) do
  stats = get_sysctl[];
  puts JSON::generate(stats);
  break unless config.include?('interval')
  sleep config['interval']
end
